/*
*  课程列表
* 
*/
var traincurriculumlistmodule = angular.module("traincurriculum",['monospaced.qrcode','angularFileUpload','ui.tree','vModal','tm.pagination','Common', 'knowledgebaseS', 'loadModule','chapterStatis','PensonSelector','btnconqitk','knowledgeDeleteBox'])
 .factory('trainStatisFactory', function (vModal) {
    return vModal({
      //  controller: 'trainstatisModal',
        controllerAs: 'trainStatisFactory',
        templateUrl: '/system/views/train/traincurriculum/trainstatis.html'
     });
 })

.controller('traincurriculumlist', ['$scope', '$stateParams','sysUserInfo', 'RequestTrainService', 'Comm', 'MsgCon', 'Msg','$state','trainStatisFactory','$rootScope',"T", function ($scope, $stateParams,sysUserInfo, RTS, Comm, MsgCon, Msg,$state,trainStatisFactory,$rootScope,T) {
$scope.coureToken = sysUserInfo.getuserinfotoken();
$scope.btnlist = { savefun: false, addinfo: false, editinfo: false, delinfo: false,exportinfo:false  };
$rootScope.btnTab = "index.Train.course";
   
      
    /**************************************初始化参数***********************************************************/
    $scope.params = {
            userid: sysUserInfo.getuserinfo().user_ID,
            startDate: "",    // 起始时间
            endDate: "", // 结束时间
            searchText: "", //搜索内容 
            searchType: 3, //筛选类型 默认时间排序
            pageIndex:1,
            pageSize:"12",
            screenText:"",
            screenType:4,
            knowledgeId:"",
            isOwner:true,
            powerLV:"",//用户身份
            orgid: sysUserInfo.getuserinfo().organization_ID,   // 企业id
            powerLV: sysUserInfo.getuserinfo().powerLV,//登录人的系统角色         
            orderby:"desc"//排序
        };
        //选择自己创建的课程
        $scope.checkOwner=function(){
            $scope.params.isOwner=!$scope.params.isOwner;
            $scope.GetList();
        }
        
        /*分页*/
        $scope.paginationConf = {
        currentPage:1,//$location.search().currentPage ? $location.search().currentPage :
        totalItems:0,
        itemsPerPage: 12,
        //pagesLength: 10,
        perPageOptions: [10, 20],
        //rememberPerPage: 'perPageItems',
        onChange: function () {
             if( (parseInt($scope.params.pageIndex) !=parseInt($scope.paginationConf.currentPage))||(parseInt($scope.params.pageSize) !=parseInt($scope.paginationConf.itemsPerPage))){
    //          console.log(parseInt($scope.params.pageIndex) !=parseInt($scope.paginationConf.currentPage));
              if($scope.paginationConf.currentPage==0){$scope.paginationConf.currentPage=1;}
              $scope.params.pageIndex =$scope.paginationConf.currentPage;
              $scope.params.pageSize = $scope.paginationConf.itemsPerPage;
              $scope.GetList();
          }
      }
    }
     //配置知识选择器
             $scope.knowConfig = {   // 配置知识选择器的参数
               menu: ["structure"],
               windowSize:"mini", //  窗口类型 standard:标准(默认:不传)  mini :迷你
                 kssMore:false, //知识结构 是否多选
                 kssList:[],    // 知识结构选中列表
                 isShow:true,  // 显示知识选择器
             }; 

             // $scope.knowConfig.isShow=true;
             /*******************************************************************************************************/
             //知识选择器查询
       $scope.onCallbackSer = function(){
            $scope.params.pageIndex = "1"; 
          if($scope.knowConfig.kssList != null && $scope.knowConfig.kssList.length >0){
            $scope.params.knowledgeId= $scope.knowConfig.kssList[0].knowledge_Id;
          }else{
            $scope.params.knowledgeId="";
          }
          $scope.GetList();
       }
   /****************************************课程共享************************************************/
    $scope.showShare=false;
    //初始共享参数
    $scope.initshare=function(){
        $scope.shareItem={
            courseIds:[],
            shareOrgId:[],
            shareOrgName:[],
            userId: sysUserInfo.getuserinfo().user_ID,
            userName: sysUserInfo.getuserinfo().user_Name,
            orgId: sysUserInfo.getuserinfo().organization_ID,
            orgName:sysUserInfo.getuserinfo().organization_Name
        }
    }
    $scope.initshare();
    //打开课程共享
   $scope.shareCourse=function(){
        $scope.showShare=!$scope.showShare;
   }
   //保存共享
   $scope.saveShare=function(){
        $scope.isloading=true;
        var saveobj=angular.copy($scope.shareItem);
        saveobj.ksclist=[];
        saveobj.orglist=[];
        RTS.addShare(saveobj).then(function (data) {
            $scope.isloading = false;
            if (data.errorcode == "0") {
                $scope.shareCourse();//关闭窗口
                Msg.success("共享成功！");
            } else {
                Msg.error(T.T("RequestDataError"));
            }
        });
   }

   /**************************************筛选显示控制***********************************************************/
 $scope.screentimeshow=false;//显示时间
 $scope.screenname=T.T("CoursewareName");
 $scope.screenlist=[{name:T.T("CoursewareName"),num:4},
 {name:T.T("EntryTime"),num:1},
 {name:T.T("TeacherOfCourse"),num:2},
 {name:T.T("Founder"),num:3}
 ];

 $scope.screenFun=function(){
    if ($scope.screenobj=="1") {
        $scope.screentimeshow=true;
    }else {
        $scope.screentimeshow=false;
    }

    switch ($scope.screenobj) {
        case"2":
        $scope.screenname=T.T("TeacherOfCourse");
        break;
        case"3":
        $scope.screenname=T.T("Founder");
        break;
        case"4":
        $scope.screenname=T.T("CoursewareName");
        break;
    }
    $scope.params.screenType=$scope.screenobj;
}
//查询按钮
$scope.ButtonGet=function(){
    $scope.params.pageIndex = "1";
    $scope.params.screenType=$scope.screenobj;
    $scope.params.screenText=$scope.searchText;
    $scope.params.startDate=document.getElementById("startTime").value;
    $scope.params.endDate=document.getElementById("endTime").value;
    $scope.GetList();

}
/**************************************排序显示***********************************************************/
        $scope.ShowOk=false;//排序显示控制
        
        //排序数组
//        $scope.OrderName="文件上传时间";
//        $scope.orderlist=[{name:"文件名称",num:1},
//        {name:"文件大小",num:2},
//        {name:"文件上传时间",num:3},
//        {name:"文件修改时间",num:4}];
        $scope.OrderName=T.T("CoursewareCreationTime");
        $scope.orderlist=[{name:T.T("CoursewareName"),num:1},
        {name:T.T("CoursewareCreationTime"),num:3},
        {name:T.T("CoursewareModificationTime"),num:4}];

        //课件排序
        $scope.OrderByFun=function(Typenum,Ordername){

            if($scope.OrderName==Ordername){
                if( $scope.params.orderby=="asc"){
                     $scope.params.orderby="desc";
                }else{
                     $scope.params.orderby="asc";
                }
            }else{
                 $scope.params.orderby="desc";
            }

            $scope.ShowOk=false;
//            if (Typenum==$scope.params.searchType) {
//                return;
//            }
            $scope.OrderName=Ordername;
            $scope.params.searchType=Typenum;
            $scope.GetList();
        }
        /**************************************查询列表***********************************************************/
    $scope.diyicijinlai = true;
     //查询课件列表
     $scope.GetList=function(){
        if($scope.isloading){
            Msg.info(T.T("InquiringPleaseWaitAmoment"));
            return;
        }
        if($scope.diyicijinlai){
            $scope.diyicijinlai= false;
            // 编辑后的回跳
           if(!Comm.isNull($stateParams.index)){             
             $scope.params.pageIndex = $stateParams.index;
           }
           if(!Comm.isNull($stateParams.screenText)){
             $scope.params.screenText = $stateParams.screenText;            
           }
           if(!Comm.isNull($stateParams.knowledgeId)){
            $scope.params.knowledgeId = $stateParams.knowledgeId;             
           }            
        }          
        $scope.isloading=true;
        $scope.params.userid=sysUserInfo.getuserinfo().user_ID;
        RTS.findCourseinfo($scope.params).then(function(data){
            $scope.isloading=false;      
            if (data.errorcode == "0") {
                $scope.List=data.datas;
                if ($scope.List.length<=0) {
                //Msg.info("暂未找到数据");
                    return;
                }else{
                    $scope.paginationConf.totalItems = data.numCount;
                    $scope.paginationConf.currentPage = data.pageIndex;  
                }
            }else{
                Msg.error(T.T("RequestDataError"));
            }
        });
  }

  /***********************************************************复选框*****************************************************/
    $scope.selectList=[];//选中之后的对象容器
    $scope.selectShow=false;
    $scope.select_all=false;
    $scope.selectAll = function() {
        $scope.select_all=!$scope.select_all;
        if ($scope.select_all) {
            $scope.selectList=angular.copy($scope.List);
        }else{
            $scope.selectList=[];
        }
    };

$scope.setCheck=function(obj){
    var index=$scope.containsList($scope.selectList,obj);
    if (index>=0) 
    {
        $scope.selectList.splice(index,1);
    }else {
        $scope.selectList.push(obj);
    }
    if ($scope.selectList.length==$scope.List.length) {
        $scope.select_all=true;
    }else{
        $scope.select_all=false;
    }
}

$scope.containsList = function (arr, obj) {
    try {
        var i = arr.length;
        while (i--) {
            if (arr[i].course_Id === obj.course_Id) {
                return i;
            }
        }
        return -1;
    } catch (e) {
            // statements
            return -1;
        }
    }
   
   /***************************************删除************************************************************/
      // 删除信息框的显示隐藏    
    $scope.deleteHide = false; //隐藏状态
    // 隐藏 用于指令回调
    $scope.cancelHide = function(){
        $scope.deleteHide = false; 
    }
    //删除按钮
    $scope.delinfo=function(){
        $scope.Del('');
    }
    $scope.delitem=null;
   //删除的参数
    $scope.delcourseid={courseids:[],confirmdel:"0",userid:sysUserInfo.getuserinfo().user_ID};
    //单个课程的删除
    $scope.Del=function(obj,index){
        $scope.delcourseid.courseids=[];
        if(!$scope.btnlist.delinfo){
            Msg.warning("无权限操作！");
            return;
        }
        $scope.isloading=true;
        if(index==0||index=="0"||index==undefined||index==""||index==null){
            $scope.delitem=obj;
            index=0;
        }else{
            obj=$scope.delitem;
        }
        $scope.delcourseid.confirmdel=index;
        $scope.IndexLength=[];
        if (obj=="") {
                if ($scope.selectList.length<=0) {
                      $scope.isloading=false;
                      return Msg.error(T.T("PleaseSelectTheDataYouWantToDelete"));
                }else {
                    $scope.selectList.forEach(function(element, index) {
                            $scope.delcourseid.courseids.push(element.course_Id);        
                    });     
                }
        }else{
            $scope.delcourseid.courseids.push(obj.course_Id);        
        }
    
        if(index==0||index=="0"){
                   //提示框
                MsgCon.delnoicon().then(function (flag) {   // 删除弹框
                    if (flag) {
                    $scope.isloading=false;
                        $scope.delcenter($scope.delcourseid,obj);
                    }else{
                        $scope.isloading=false;
                    }
                });
        //删除关系       
        }else{
               //提示框
                $scope.isloading=true;
                $scope.delcenter($scope.delcourseid,obj);
          }
}
//删除分离出来的方法
$scope.delcenter=function(param,obj){

            RTS.delCourse(param).then(function(data){
                $scope.isloading=false;
                if (data.errorcode == "0") {
                    $scope.delcourseid.courseids=[];
                    Msg.success(T.T("DeleteSuccessfully"));
                     $scope.deleteHide = false; 
                        $scope.delitem=null;
                     if (obj=="") {          
                        $scope.selectList.forEach(function(element, index) {    
                            $scope.List.splice($scope.containsList($scope.List,element),1);
                        });        
                       
                    }else{
                        $scope.List.splice($scope.containsList($scope.List,obj),1);
                    }
                    $scope.selectList=[];      
                } else if (data.errorcode == "34") {        
                    $scope.deleteList = data.datas;
                    $scope.deleteHide = true;   // 显示关联窗口
                }else{
                    Msg.error(T.T("RequestDataError"));
                }
            }); 
}
  /*******编辑、保存********/

  $scope.addinfo=function(){
        $scope.Edit(0);
  }
      
    $scope.Edit=function(obj){        
        
        if(!$scope.btnlist.addinfo){
            Msg.warning("无权限操作！");
            return;
        }
        var studyCount=0;
        if(obj.slist!=undefined&&obj.slist.user_id!=undefined&&obj.slist.user_id.length>0){
            studyCount=obj.slist.user_id;
        }
        $state.go("index.Train.course.lukecheng",{courid:obj.course_Id,studycount:studyCount,index:$scope.paginationConf.currentPage,screenText:$scope.params.screenText,knowledgeId:$scope.params.knowledgeId});        
    }     
      var lorem = { courseid: '',sendFlag: false,objinfo:null };
    //统计
    $scope.opentrainstatic = function (traininfo) {        
         lorem.courseid = traininfo.course_Id;
         trainStatisFactory.activate(lorem);        
    }
    //预览
    $scope.openKe = function (traininfo) {        

        //预览
        var url = "";
        if ($rootScope.fileurl.indexOf("http") != -1) {
            url = $rootScope.upurl + '/dispatcher/redirect?url=' + encodeURI(encodeURI($rootScope.fileurl + "/resources/template/" +traininfo.course_Id + ".html&token=" + sysUserInfo.getuserinfotoken()));
        } else {
            url = $rootScope.upurl + '/dispatcher/redirect?url=' + encodeURI(encodeURI(window.location.protocol  + $rootScope.fileurl + "/resources/template/" + traininfo.course_Id + ".html&token=" + sysUserInfo.getuserinfotoken()));
        }
        window.open(url);
    }

    /*****************************************************课程共享*************************************************/
    $scope.shareCourse={
        courseList:[]
    };//共享的课程
    $scope.showShare=false;//是否显示弹框
    //打开共享
    $scope.openShare=function(){
        if($scope.selectList.length<=0){
            Msg.warning("请至少选择一门课程！");
            return;
        }else{
            $scope.shareCourse.courseList=$scope.selectList;
        }
        $scope.showShare=true;
    }
    //关闭的回调事件
    $scope.closeShare=function(){
        $scope.showShare=false;
    }
} ]);
